/**
 * Created by zhang_j on 2020/7/6
 */
public class 两数相除 {

    public static void main(String[] args) {
        System.out.println(divide(-10, -3));
        System.out.println(divide(-2147483648, -1));
        System.out.println(divide(-2147483648, 1));
        System.out.println(divide(-2147483648, 2));
        System.out.println(divide(-2147483648, -2));
    }

    public static int divide(int dividend, int divisor) {
        boolean negative = false;
        if((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0)){
            negative = true;
        }
        if(divisor == -1){
            if(dividend == Integer.MIN_VALUE){
                return Integer.MAX_VALUE;
            }else{
                return -dividend;
            }
        }
        if(divisor == 1){
            return dividend;
        }
        long newDividend = (long)dividend;
        long newDivisor = (long)divisor;
        newDividend = Math.abs(newDividend);
        newDivisor = Math.abs(newDivisor);
        long tmp = div(newDividend, newDivisor);
        int result = tmp > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)tmp;
        return negative ? -result : result;
    }

    private static long div(long a, long b){
        if(a < b){
            return 0;
        }
        long tb = b;
        long count = 1;
        while((tb +tb) <= a){
            count += count;
            tb += tb;
        }
        return count + div(a - tb, b);
    }
}
